package org.edu.converter;

import java.io.Serializable;
import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.edu.model.Sciency;
import org.springframework.transaction.annotation.Transactional;

@FacesConverter("sciencyIdConverter")
public class SciencyIdConverter implements Converter, Serializable{

	private static final long serialVersionUID = 1L;

	@Transactional
	public Object getAsObject(FacesContext context, UIComponent component,	String value) {
		if (value != null) {
			return this.getAttributesFrom(component).get(value);
		}
		return null;
	}

	@Transactional
	public String getAsString(FacesContext context, UIComponent component,	Object value) {
		if (value != null && !"".equals(value)) {
			Sciency sciency = (Sciency) value;
			this.addAttribute(component, sciency);
			Long Id = sciency.getSciency_id();
			if(Id != null){
				return String.valueOf(Id);
			}
		}
		return (String) value;
	}

	protected void addAttribute(UIComponent component, Sciency sciencyp) {
		String key = sciencyp.getSciency_id().toString();
		this.getAttributesFrom(component).put(key, sciencyp);
	}

	protected Map<String, Object> getAttributesFrom(UIComponent component) {
		return component.getAttributes();
	}
}
